import React from 'react';
import { Form, Modal, Button, Transfer } from 'antd';
import { connect } from 'dva';

const entityNameSpace = 'table';

@connect(({ table, loading }) => ({
  table,
  loading: loading.models.table,
}))
class DataInfoForm extends React.Component {
  completeCallBack;
  projectId;

  state = {
    visible: false,
    radioDisable: false,
    targetKeys: [],
  };

  componentDidMount() {
    const { dispatch, projectId } = this.props;
    this.props.onRef(this);

    dispatch({
      type: `${entityNameSpace}/getProjectApi`,
      payload: projectId,
      callback:res=>this.setState({targetKeys:eval(res.ignoreTables)})
    });

  }

  handleReloadTableList = () => {
    const { dispatch, projectId } = this.props;

    dispatch({
      type: `${entityNameSpace}/queryEntityPageList`,
      payload: { projectId: projectId },
    });


  };


  handleChange = (targetKeys, direction, moveKeys) => {
    const { dispatch,projectId } = this.props;
    this.setState({targetKeys:targetKeys})

    let data ={};
    data.id = projectId;
    data.ignoreTables = JSON.stringify(targetKeys);

    dispatch({
      type: `${entityNameSpace}/updateProject`,
      payload: data,
    });

  };

  renderItem = item => {
    const customLabel = (
      <span className="custom-item">
        {item.title} - {item.description}
      </span>
    );

    return {
      label: customLabel, // for displayed item
      value: item.title, // for title and filter matching
    };
  };

  handleModalVisible = (visible, callBack, id) => {
    this.completeCallBack = callBack;
    const { form } = this.props;
    this.setState({
      ...this.state,
      visible: visible,
      radioDisable: id ? true : false,
    });
    if (visible) {
      // form reset
      form.resetFields();
      this.projectId = id;
      this.handleReloadTableList()
    }
  };

  handleCancel = () => {
    this.setState({
      ...this.state,
      visible: false
    });
  };


  render() {
    const {
      [entityNameSpace]: { entityPageResult },
    } = this.props;

    let data = [];
    for (let d of entityPageResult.list) {
      let obj = {};
      obj.key = d.id;
      obj.title = d.name;
      obj.description = d.comment;
      data.push(obj)
    }

    const { visible } = this.state;
    return (
      <Modal
        width={800}
        visible={visible}
        keyboard={false}
        maskClosable={false}
        title="项目详情"
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        footer={[
          <Button key="back" onClick={this.handleCancel}>
            关闭
          </Button>,
        ]}
      >
        <Transfer
          dataSource={data}
          listStyle={{
            width: 300,
            height: 300,
          }}
          targetKeys={this.state.targetKeys}
          onChange={this.handleChange}
          render={this.renderItem}
        />
      </Modal>
    );
  }
}

export default Form.create()(DataInfoForm);
